//引入express
const express = require('express')
const cors = require('cors')

//创建服务对象
const app = express()
//应用cors中间件，用于解决跨域问题
app.use(cors())
//使用express.urlencoded中间件，用于解析请求体urlencoded编码的参数
app.use(express.urlencoded({extended:true}))
//使用express.json中间件，用于解析请求体json编码的参数
app.use(express.json())


//响应get请求，不接收参数，只是单纯返回固定数据
app.get('/hello',(request,response)=>{
	console.log('有人找我要欢迎信息了')
	response.send('你好啊???')
})

//响应get请求，接收query参数，且为urlencoded，返回求和结果
app.get('/increment',(request,response)=>{
	//获取传过来的参数
	const {n1,n2} = request.query
	const result = n1*1 + n2*1
	response.send(result.toString())
})

//响应get请求，接收params参数，返回求和结果
app.get('/increment/:n1/:n2',(request,response)=>{
	//获取传过来的参数
	const {n1,n2} = request.params
	const result = n1*1 + n2*1
	response.send(result.toString())
})

//响应post请求，接收query参数，且为urlencoded，返回求和结果
/* app.post('/increment',(request,response)=>{
	//获取传过来的参数
	const {n1,n2} = request.query
	const result = n1*1 + n2*1
	response.send(result.toString())
}) */

//响应post请求，接收params参数，返回求和结果
/* app.post('/increment/:n1/:n2',(request,response)=>{
	//获取传过来的参数
	const {n1,n2} = request.params
	const result = n1*1 + n2*1
	response.send(result.toString())
}) */

//响应post请求，接收请求体参数，返回求和结果
app.post('/increment',(request,response)=>{
	//获取传过来的参数
	const {n1,n2} = request.body
	console.log('%',n1,n2)
	const result = n1*1 + n2*1
	response.send(result.toString())
}) 

//响应get请求,不接收参数
app.get('/persons',(request,response)=>{
	console.log('@#$')
	const persons = [
		{id:'001',name:'老刘',sex:'女'},
		{id:'002',name:'阿峰',sex:'女'},
		{id:'003',name:'张三',sex:'男'}
	]
	setTimeout(()=>{
		response.send(persons)
	},4000)
})

app.get('/cars',(request,response)=>{
	const persons = [
		{id:'001',name:'阿特兹',price:'30万'},
		{id:'002',name:'雷克萨斯',sex:'40万'},
	]
	setTimeout(()=>{
		response.send(persons)
	},4000)
})

app.get('/code',(request,response)=>{
	const c = Math.floor(1000 + 8999*Math.random())
	setTimeout(()=>{
		response.send(c.toString())
	},3000)
})

//绑定端口监听
app.listen(5000,(error)=>{
	if(!error) console.log('服务器启动成功了！')
	else console.log('服务器启动失败！')
})

